package com.vdong.interactive.course.dubbo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.vdong.interactive.course.common.enums.PeddleGoodsApplyStatusEnum;
import com.vdong.interactive.course.common.enums.PeddleGoodsOpenEnum;
import com.vdong.interactive.course.entity.dto.GoodsPeddleSubmitDTO;
import com.vdong.interactive.course.entity.dto.IndexAddGoodsDTO;
import com.vdong.interactive.course.entity.dto.PeddleGoodsOperationDTO;
import com.vdong.interactive.course.entity.dto.base.BasePeddleGoodsDTO;
import com.vdong.interactive.course.entity.mo.Goods;
import com.vdong.interactive.course.entity.mo.GoodsPeddle;
import com.vdong.interactive.course.facade.PeddleGoodsFacadeService;
import com.vdong.interactive.course.repository.dao.GoodsMapper;
import com.vdong.interactive.course.repository.dao.GoodsPeddleMapper;
import com.vdong.interactive.course.service.PeddleGoodsService;
import com.vdong.kpay.basics.dubbo.api.backend.StoreService;
import com.vdong.kpay.basics.dubbo.pojo.backend.StoreInfo;
import lombok.extern.log4j.Log4j2;
import org.lamb.framework.common.exception.EventException;
import org.lamb.framework.common.util.FacadeResultUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@org.springframework.stereotype.Service
/**
 * 分销商品
 */
@Log4j2
public class PeddleGoodsFacadeServiceImpl implements PeddleGoodsFacadeService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsPeddleMapper goodsPeddleMapper;

    @Autowired
    private PeddleGoodsService peddleGoodsService;

    @Reference(version = "1.0.0")
    private StoreService storeService;

    private static final String PREFIX = "http://";

    @Override
    @Transactional
//    public void addPeddleGoods(GoodsPeddleSubmitDTO goodsPeddleDTO){
    public String addPeddleGoods(String params){

        GoodsPeddleSubmitDTO goodsPeddleDTO = JSON.parseObject(params, GoodsPeddleSubmitDTO.class);
        GoodsPeddle selectCount = new GoodsPeddle();
        selectCount.setPlatformGoodsId(goodsPeddleDTO.getGoodsId());
        selectCount.setDeleted(false);
        selectCount.setCheckState(PeddleGoodsApplyStatusEnum.CHECK_FAILURE.getCode());
        List<GoodsPeddle> goodsPeddleList = goodsPeddleMapper.select(selectCount);

        if (goodsPeddleList != null){

            goodsPeddleList.forEach(goodsPeddle->{
                log.info("***************************删除商品！***********************************" + goodsPeddle.getId());
                goodsPeddleMapper.deleteByPrimaryKey(goodsPeddle.getId());
                goodsMapper.deleteByPrimaryKey(goodsPeddle.getGoodsId());
            });
        }

        GoodsPeddle selectGoods = new GoodsPeddle();
        selectGoods.setPlatformGoodsId(goodsPeddleDTO.getGoodsId());
        selectGoods.setDeleted(false);
        int count = goodsPeddleMapper.selectCount(selectGoods);

        if (count > 0){
            log.info("***************************" + goodsPeddleDTO.getGoodsId() + "已经参加分销！***********************************");
            return FacadeResultUtils.failFacadeBeanToString("该商品已参加分销！");
        }

        try {
            Date currentDateTime = new Date();
            Goods goods = new Goods();
            BeanUtils.copyProperties(goodsPeddleDTO, goods);
            goods.setDeleted(false);
            goods.setCreateDate(currentDateTime);
            goods.setCreateUser(goodsPeddleDTO.getSysUserId());
            goods.setModifyDate(currentDateTime);
            goods.setModifyUser(goodsPeddleDTO.getSysUserId());
            goods.setPlatformId(goodsPeddleDTO.getPlatformId());
            goodsMapper.insertSelective(goods);
            GoodsPeddle goodsPeddle = new GoodsPeddle();
            BeanUtils.copyProperties(goodsPeddleDTO, goodsPeddle);
            goodsPeddle.setGoodsId(goods.getId());
            goodsPeddle.setCheckState(PeddleGoodsApplyStatusEnum.CHECK_PENDING.getCode());
            goodsPeddle.setOpenState(PeddleGoodsOpenEnum.LOWER_SHELF.getCode());
            goodsPeddle.setCheckDate(currentDateTime);
            goodsPeddle.setModifyDate(currentDateTime);
            goodsPeddle.setCreateDate(currentDateTime);
            goodsPeddle.setSubmitDate(currentDateTime);
            goodsPeddle.setDeleted(false);
            goodsPeddle.setCreateUser(goodsPeddleDTO.getSysUserId());
            goodsPeddle.setModifyUser(goodsPeddleDTO.getSysUserId());
            goodsPeddle.setPlatformGoodsId(goodsPeddleDTO.getGoodsId());
            goodsPeddle.setIsShow(false);
            goodsPeddle.setSubType(Integer.parseInt(goodsPeddleDTO.getSubType()));
            goodsPeddle.setPlatformProfitRatio(goodsPeddleDTO.getPlatformRate());
            goodsPeddle.setPromoterProfitRatio(goodsPeddleDTO.getPeddleRate());
            goodsPeddle.setClassifyType(goodsPeddleDTO.getGoodsType());
            goodsPeddle.setOpenDate(currentDateTime);
            goodsPeddle.setAuthorId(goodsPeddleDTO.getAuthorId());
            goodsPeddle.setAuthorName(goodsPeddleDTO.getAuthorName());
            StoreInfo storeInfo = storeService.getStoreBaseInfo(goodsPeddleDTO.getPlatformInsideId());
            goodsPeddle.setPlatformStoreName(storeInfo.getName());
            goodsPeddle.setPlatformStoreId(goodsPeddleDTO.getPlatformInsideId());
            goodsPeddle.setPlatformStoreName(storeService.getStoreBaseInfo(goodsPeddleDTO.getPlatformInsideId()).getName());
            goodsPeddleMapper.insertSelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("提交失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String editPeddleGoods(String params){
        try {
            GoodsPeddleSubmitDTO goodsPeddleDTO = JSON.parseObject(params, GoodsPeddleSubmitDTO.class);
            Date currentDateTime = new Date();
            GoodsPeddle goodsPeddle = goodsPeddleMapper.selectByPrimaryKey(goodsPeddleDTO.getId());
            goodsPeddle.setModifyDate(currentDateTime);
            goodsPeddle.setPromoterProfitRatio(goodsPeddleDTO.getPeddleRate());
            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
            Goods goods = Goods.builder()
                    .id(goodsPeddle.getGoodsId())
                    .price(goodsPeddleDTO.getPrice()).build();

            goodsMapper.updateByPrimaryKeySelective(goods);

        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("提交失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String checkPeddleGoods(String params){
        try {
            PeddleGoodsOperationDTO operation = JSON.parseObject(params, PeddleGoodsOperationDTO.class);
            Date currentDateTime = new Date();
            GoodsPeddle goodsPeddle = goodsPeddleMapper.selectOne(GoodsPeddle.builder().goodsId(operation.getPeddleGoodsId()).build());

            if (Objects.isNull(goodsPeddle)) {
                // TODO 抛异常
            }

            if (PeddleGoodsApplyStatusEnum.CHECK_PASS.getCode().compareTo(operation.getStatus()) == 0) {
                //审核通过
                goodsPeddle = GoodsPeddle.builder()
                        .id(operation.getPeddleGoodsId())
                        .checkDate(currentDateTime)
                        .modifyDate(currentDateTime)
                        .openDate(currentDateTime)
                        .checkState(PeddleGoodsApplyStatusEnum.CHECK_PASS.getCode())
                        .openState(PeddleGoodsOpenEnum.PUTAWAY.getCode()).build();
            } else if (PeddleGoodsApplyStatusEnum.CHECK_FAILURE.getCode().compareTo(operation.getStatus()) == 0) {
                //审核不通过
                goodsPeddle = GoodsPeddle.builder()
                        .id(operation.getPeddleGoodsId())
                        .checkDate(currentDateTime)
                        .modifyDate(currentDateTime)
                        .checkState(PeddleGoodsApplyStatusEnum.CHECK_FAILURE.getCode())
                        .auditNote(operation.getNote()).build();
            }

            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("审核失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String addViolationPeddleGoods(String params){
        try {
            PeddleGoodsOperationDTO operation = JSON.parseObject(params, PeddleGoodsOperationDTO.class);
            Date currentDateTime = new Date();
            GoodsPeddle goodsPeddle = goodsPeddleMapper.selectByPrimaryKey(operation.getPeddleGoodsId());

            if (Objects.isNull(goodsPeddle)) {
                // TODO 抛异常
            }

            goodsPeddle = GoodsPeddle.builder()
                    .id(operation.getPeddleGoodsId())
                    .modifyDate(currentDateTime)
                    .checkState(PeddleGoodsApplyStatusEnum.VIOLATION.getCode())
                    .auditNote(operation.getNote())
                    .handleDate(currentDateTime)
                    .openState(PeddleGoodsOpenEnum.LOWER_SHELF.getCode())
                    .illegalNote(operation.getNote()).build();

            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("添加失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String delViolationPeddleGoods(String params){
        try {
            PeddleGoodsOperationDTO operation = JSON.parseObject(params, PeddleGoodsOperationDTO.class);
            GoodsPeddle goodsPeddle = goodsPeddleMapper.selectByPrimaryKey(operation.getPeddleGoodsId());
            Goods goods = goodsMapper.selectByPrimaryKey(goodsPeddle.getGoodsId());
            goods.setDeleted(true);
            goodsPeddle.setDeleted(true);
            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
            goodsMapper.updateByPrimaryKeySelective(goods);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("移除失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String addIndexPeddleGoods(String params){
        try {
            IndexAddGoodsDTO operation = JSON.parseObject(params, IndexAddGoodsDTO.class);
            Date currentDateTime = new Date();

            List<Long> peddleGoodsIds = operation.getPeddleGoodsIds();

            peddleGoodsIds.forEach(e -> {
                GoodsPeddle goodsPeddle = GoodsPeddle.builder()
                        .id(e)
                        .modifyDate(currentDateTime)
                        .isShow(true).build();

                goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
            });

        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("添加失败！");
        }
        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String delIndexPeddleGoods(String params){
        try{
            PeddleGoodsOperationDTO operation = JSON.parseObject(params,PeddleGoodsOperationDTO.class);
            Date currentDateTime = new Date();
            GoodsPeddle goodsPeddle = GoodsPeddle.builder()
                    .id(operation.getPeddleGoodsId())
                    .modifyDate(currentDateTime)
                    .isShow(false).build();

            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("移除失败！");
        }

        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    @Transactional
    public String openStatePeddleGoods(String params){
        try{
            PeddleGoodsOperationDTO operation = JSON.parseObject(params,PeddleGoodsOperationDTO.class);
            Date currentDateTime = new Date();
            GoodsPeddle goodsPeddle = null;

            if (PeddleGoodsOpenEnum.PUTAWAY.getCode().compareTo(operation.getStatus()) == 0){
                goodsPeddle = GoodsPeddle.builder()
                        .id(operation.getPeddleGoodsId())
                        .modifyDate(currentDateTime)
                        .openState(PeddleGoodsOpenEnum.PUTAWAY.getCode())
                        .openDate(currentDateTime).build();
            }else if (PeddleGoodsOpenEnum.LOWER_SHELF.getCode().compareTo(operation.getStatus()) == 0){
                goodsPeddle = GoodsPeddle.builder()
                        .id(operation.getPeddleGoodsId())
                        .modifyDate(currentDateTime)
                        .openState(PeddleGoodsOpenEnum.LOWER_SHELF.getCode()).build();
            }else{
                return FacadeResultUtils.failFacadeBeanToString("操作失败！");
            }

            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("操作失败！");
        }

        return FacadeResultUtils.succFacadeBeanToString();
    }

    @Override
    public String getBasePeddleGoodsDetail(String params){
        BasePeddleGoodsDTO peddleGoods = JSON.parseObject(params,BasePeddleGoodsDTO.class);
        BasePeddleGoodsDTO peddleGoodsDetail = peddleGoodsService.getBasePeddleGoodsDetail(peddleGoods.getPeddleGoodsId());
        return FacadeResultUtils.succFacadeBeanToString(peddleGoodsDetail);
    }

    @Override
    public String peddleGoodsSalesNumUpdate(String params){
        try {
            BasePeddleGoodsDTO paramsObject = JSON.parseObject(params,BasePeddleGoodsDTO.class);
            GoodsPeddle goodsPeddle = new GoodsPeddle();
            goodsPeddle.setId(paramsObject.getPeddleGoodsId());
            goodsPeddle.setSalesNum(paramsObject.getSalesNum());
            goodsPeddleMapper.updateByPrimaryKeySelective(goodsPeddle);
        }catch (Exception e){
            return FacadeResultUtils.failFacadeBeanToString("更新失败！");
        }

        return FacadeResultUtils.succFacadeBeanToString();
    }

}
